﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;

namespace G.Reader.View
{
    public partial class UserLoginPage : GBasePage, G.Reader.Utils.ILogin
    {
        UserInfoService.UserInfoServiceClient userInfoServiceClient = new UserInfoService.UserInfoServiceClient();
        PushService.PushServiceClient pushServiceClient = new PushService.PushServiceClient();
        public UserLoginPage()
        {
            InitializeComponent();
            userInfoServiceClient.RegisterUserCompleted += new EventHandler<UserInfoService.RegisterUserCompletedEventArgs>(userInfoServiceClient_RegisterUserCompleted);
            userInfoServiceClient.LoginCompleted += new EventHandler<UserInfoService.LoginCompletedEventArgs>(userInfoServiceClient_LoginCompleted);
            pushServiceClient.UpdatePushInfoCompleted += new EventHandler<PushService.UpdatePushInfoCompletedEventArgs>(pushServiceClient_UpdatePushInfoCompleted);
        }

        void pushServiceClient_UpdatePushInfoCompleted(object sender, PushService.UpdatePushInfoCompletedEventArgs e)
        {
            if (e.Result.IsOk)
            {
                GloabalData.Instance.PushInfo = e.pushinfo;
                if (this.LoginSuccessCallback == null)//如果LoginSuccessCallback为空，那么直接返回，发生这种情况只有一种可能，那就是程序墓碑
                    this.NavigationService.GoBack();
                else
                {
                    this.LoginSuccessCallback(true);
                    if (!this.IsFoward)//如果不是Foward，那么说明登录完成后直接返回前一页
                    {
                        this.NavigationService.GoBack();
                    }
                }
            }
        }



        void userInfoServiceClient_LoginCompleted(object sender, UserInfoService.LoginCompletedEventArgs e)
        {
            if (e.Result.IsOk)
            {
                GloabalData.Instance.User = e.userinfo;
                if (this.LoginSuccessCallback == null)//如果LoginSuccessCallback为空，那么直接返回，发生这种情况只有一种可能，那就是程序墓碑
                    this.NavigationService.GoBack();
                else
                {
                    if (GloabalData.Instance.PushInfo == null)
                    {
                        this.LoginSuccessCallback(true);
                        if (!this.IsFoward)//如果不是Foward，那么说明登录完成后直接返回前一页
                        {
                            this.NavigationService.GoBack();
                        }
                    }
                    else
                    {
                        GloabalData.Instance.PushInfo.UserId = e.userinfo.Id;
                        pushServiceClient.UpdatePushInfoAsync(GloabalData.Instance.PushInfo);
                    }
                }
            }
            else
            {
                MessageBox.Show(e.Result.Message);
                txtPassword.Password = "";
                EnableApplicationBar();
                pb.Visibility = System.Windows.Visibility.Collapsed;
                pb.Stop();
            }

        }

        void userInfoServiceClient_RegisterUserCompleted(object sender, UserInfoService.RegisterUserCompletedEventArgs e)
        {
            if (e.Result.IsOk)
            {
                if (this.LoginSuccessCallback == null)//如果LoginSuccessCallback为空，那么直接返回，发生这种情况只有一种可能，那就是程序墓碑
                    this.NavigationService.GoBack();
                else
                {
                    this.ShowState("注册成功!正在登录！");
                    this.userInfoServiceClient.LoginAsync(txtEmail.Text, System.Security.Cryptography.MD5.GetHashString(txtPwd.Password));
                }
            }
            else
            {
                MessageBox.Show(e.Result.Message);
            }
            //EnableApplicationBar();
            //pb.Visibility = System.Windows.Visibility.Collapsed;
            //pb.Stop();
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New && !e.Uri.OriginalString.StartsWith("app://external/"))
            {
                this.NavigationService.RemoveBackEntry();
            }
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (LoginSuccessCallback != null)
            {
                LoginSuccessCallback(false);
            }
            base.OnBackKeyPress(e);
        }

        private void Send_Click(object sender, EventArgs e)
        {
            this.Focus();
            DoSend();
        }
        private void Send_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                DoSend();
        }

        private void DoSend()
        {  //用户登录
            if (pivot.SelectedIndex.Equals(0))
            {
                string userName = txtUserName.Text.Trim();
                if (string.IsNullOrEmpty(userName))
                {
                    MessageBox.Show("请输入用户名！");
                    return;
                }
                string password = txtPassword.Password.Trim();
                if (string.IsNullOrEmpty(password))
                {
                    MessageBox.Show("请输入密码！");
                    return;
                }
                DisableApplicationBar();
                pb.Visibility = System.Windows.Visibility.Visible;
                pb.Start();
                userInfoServiceClient.LoginAsync(userName, System.Security.Cryptography.MD5.GetHashString(password));
            }
            else   //用户注册
            {
                string email = txtEmail.Text.Trim();
                string password = txtPwd.Password.Trim();
                string confirmPwd = txtConPwd.Password.Trim();
                if (email == string.Empty)
                {
                    MessageBox.Show("请输入用户名");
                    return;
                }
                if (password == string.Empty)
                {
                    MessageBox.Show("请输入密码");
                    txtPwd.Password = string.Empty;
                    txtConPwd.Password = string.Empty;
                    return;
                }
                if (!Regex.IsMatch(email, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    MessageBox.Show("用户名为邮箱格式");
                    return;
                }
                else
                {
                    if (password.Length < 6 || password.Length > 16)
                    {
                        MessageBox.Show("密码为6-16位字母或数字");
                        return;
                    }
                    else
                    {
                        if (!password.Equals(confirmPwd))
                        {
                            MessageBox.Show("密码不一致");
                            return;
                        }
                        else
                        {
                            DisableApplicationBar();
                            pb.Visibility = System.Windows.Visibility.Visible;
                            pb.Start();
                            userInfoServiceClient.RegisterUserAsync(email, password, txtNickName.Text);
                        }
                    }
                }

            }
        }
        private void DisableApplicationBar()
        {
            ApplicationBarIconButton btnSend = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            btnSend.IsEnabled = false;
        }
        private void EnableApplicationBar()
        {
            ApplicationBarIconButton btnSend = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            btnSend.IsEnabled = true;
        }


        public Action<bool> LoginSuccessCallback
        {
            get;
            set;
        }

        public bool IsFoward
        {
            get;
            set;
        }
    }
}